package com.iarc.base.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Process
import android.text.TextUtils
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.iarc.base.BaseApp
import com.iarc.base.bugly.BuglyUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
import kotlin.system.exitProcess


object AppUtil {

    /**
     * 获取当前进程pid
     */
    fun getAlivePid(processName: String, context: Context): Int {
        val mActivityManager =
//            ContextCompat.getSystemService(context, Context.ACTIVITY_SERVICE) as ActivityManager
            ContextCompat.getSystemService(context, ActivityManager::class.java)
        mActivityManager?.let {
            for (appProcess in it.runningAppProcesses) {
                if (appProcess.processName == processName) {
                    LogUtils.loge("${appProcess.pid}")
                    return appProcess.pid
                }
            }
        }

        return -1
    }

    /**
     * @param time time
     * @desc 字符串转时间戳
     * @example time="2019-04-19"
     */
    @SuppressLint("SimpleDateFormat")
    fun getTimestamp(time: String): Long? {
        var timestamp: Long? = null
        try {
            timestamp =
                Objects.requireNonNull(SimpleDateFormat("yyyy-MM-dd").parse(time)).time / 1000
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return timestamp
    }

//    fun getScreenWidth(context:Context) {
//        val outMetrics = DisplayMetrics()
//        windowManager.defaultDisplay.getMetrics(outMetrics)
//        val widthPixels = outMetrics.widthPixels
//        val heightPixels = outMetrics.heightPixels
//        LogUtils.loge("widthPixels = $widthPixels,heightPixels = $heightPixels")
//    }

    /**
     * @param time
     * @return
     * @desc 时间戳转日期
     */
    @SuppressLint("SimpleDateFormat")
    fun convertTimestamp2Date(time: Long): String {
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return simpleDateFormat.format(Date(time))
    }

    /**
     * @desc 日期转时间戳
     */
    @SuppressLint("SimpleDateFormat")
    fun convertDate2Time(time: String): Long {
        return SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(time, ParsePosition(0))?.time ?: 0
    }

    /**
     * 近3天时间范围  不包括今天
     */
    fun nearly3Days(): LongArray {
        return nearlyDays(3)
    }


    /**
     * 近几天天时间范围  不包括今天
     */
    fun nearlyDays(days: Int): LongArray {
        val result = LongArray(2)
        val startTimeStr =
            "${convertTimestamp2Date2(System.currentTimeMillis() - 24 * 60 * 60 * 1000 * days)} 00:00:00"
        val endTimeStr =
            "${convertTimestamp2Date2(System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 1)} 23:59:59"

        result[0] = convertDate2Time(startTimeStr)
        result[1] = convertDate2Time(endTimeStr)
        return result
    }

    /**
     * 时间ms 转天数  不足一天按照一天计算
     */
    fun time2Days(time: Long): String {
        val days = time / (24 * 60 * 60 * 1000) + 1
        return days.toString()
    }

    /**
     * 时间ms 转天&小时(小时不足1小时 按照1小时计算)
     */
    fun time2DaysHours(time: Long): String {
        var result = ""
        var days = 0L
        var hours = 0L
        days = time / (24 * 60 * 60 * 1000)
        hours = (time - (days * 24 * 60 * 60 * 1000)) / (60 * 60 * 1000) + 1
        return if (days == 0L) "${hours}小时" else "${days}天${hours}小时"
    }

    @SuppressLint("SimpleDateFormat")
    fun convertTimestamp2Date2(time: Long): String {
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd")
        return simpleDateFormat.format(Date(time))
    }

    @get:SuppressLint("HardwareIds")
    val deviceSN: String
        get() = Build.SERIAL

    /*
     * 是否为浮点数？double或float类型。
     * @param str 传入的字符串。
     * @return 是浮点数返回true,否则返回false。
     */
    fun isDoubleOrFloat(str: String?): Boolean {
        val pattern = Pattern.compile("^[-\\+]?[.\\d]*$")
        return pattern.matcher(str).matches()
    }

    /**
     * 重启应用程序
     */
    fun restartApplication() {
        val intent =
            BaseApp.instance.packageManager.getLaunchIntentForPackage(BaseApp.instance.packageName)
        intent!!.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        BaseApp.instance.startActivity(intent)
        Process.killProcess(Process.myPid())
        exitProcess(0)
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private fun getProcessName(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName: String = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim { it <= ' ' }
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                reader?.close()
            } catch (exception: IOException) {
                exception.printStackTrace()
            }
        }
        return null
    }
}